import * as vscode from 'vscode';
import { VerticalDiffCodeLensProvider } from '../diff/vertical/VerticalPerLineCodeLensProvider';
import { VerticalDiffHandler } from '../diff/vertical/handler';
import { ChatMessage } from '../../core';
import {streamDiffLines} from "../../core/edit/streamDiffLines"

const { registerCodeLensProvider } = vscode.languages;

export interface VerticalDiffCodeLens {
    start: number;
    numRed: number;
    numGreen: number;
}

/**
 * 流式输出到编辑器
 */
export class StreamInlineEdit {
    private range?: vscode.Range;
    private streamChat:AsyncGenerator<ChatMessage>;


    constructor(
        streamChat:AsyncGenerator<ChatMessage>,
        range?: vscode.Range
    ){
        this.range = range;
        this.streamChat = streamChat;
    }

    public async streamInlineEdit(){
        let editor = vscode.window.activeTextEditor;

        if (!editor) {
          return undefined;
        }
        const fileUri = editor.document.uri.toString();
    
        let startLine, endLine: number;
    
        if (this.range) {
          startLine = this.range.start.line;
          endLine = this.range.end.line;
        } else {
          startLine = editor.selection.start.line;
          endLine = editor.selection.end.line;
        }

        await new Promise((resolve) => {
            setTimeout(resolve, 200);
          });

        let fileUriToCodeLens: Map<string, VerticalDiffCodeLens[]> = new Map();

        let provider = new VerticalDiffCodeLensProvider(
            fileUriToCodeLens,
        );
    
        registerCodeLensProvider(
            "*",
            provider,
        );
    
        const diffHandler = new VerticalDiffHandler(
        startLine,
        endLine,
        editor,
        fileUriToCodeLens,
        ()=> {},
        provider.refresh.bind(provider),
        {input:"", onStatusUpdate: () => {}},
        );


        let selectedRange = diffHandler.range;
        // 获取选中的文本
        const rangeContent = editor.document.getText(selectedRange);

        const streamedLines: string[] = [];
        let stream_Chat = this.streamChat
        async function* recordedStream() {
            const stream = streamDiffLines(rangeContent,stream_Chat);
            for await (const line of stream) {
              if (line.type === "new" || line.type === "same") {
                streamedLines.push(line.line);
              }
              yield line;
            }
          }
          await diffHandler.run(recordedStream());
    }

}
